package cn.fzc.elasticsearch2x.service;

import cn.fzc.elasticsearch2x.dao.InvoiceDetailRepository;
import cn.fzc.elasticsearch2x.entity.InvoiceDetail;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


@Service
public class InvoiceDetailService {

    @Autowired
    private InvoiceDetailRepository repository;


    InvoiceDetail findBYId(String id) {
        return repository.findOne(id);
    }

    void save(InvoiceDetail invoiceDetail) {
        repository.save(invoiceDetail);
    }

    Page<InvoiceDetail> findByPage(int current, int Size) {
        //创建builder
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder下有must、should以及mustNot 相当于sql中的and、or以及not
        //设置模糊搜索,真实姓名中包含金的用户
        builder.must(QueryBuilders.rangeQuery("total_amount").gt(0));

        builder.mustNot(QueryBuilders.existsQuery("buyer_taxnum"));

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("total_amount").gt(0);

        //排序
//        FieldSortBuilder sort = SortBuilders.fieldSort("update_time").order(SortOrder.DESC);

        //设置分页
        //====注意!es的分页和Hibernate一样api是从第0页开始的=========
        PageRequest page = new PageRequest(current, Size);

        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //将搜索条件设置到构建中
        nativeSearchQueryBuilder.withQuery(rangeQueryBuilder);
        //将分页设置到构建中
        nativeSearchQueryBuilder.withPageable(page);
        NativeSearchQuery query = nativeSearchQueryBuilder.build();

        //执行,返回包装结果的分页
        Page<InvoiceDetail> resutlList = repository.search(query);
        return resutlList;
    }

    Page<InvoiceDetail> findAll(int current, int Size) {
        return repository.findAll(new PageRequest(current, Size));
    }


}
